#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/06/27
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from datetime import datetime
from project.flasky import db
from project.define import db_logger


DataName = "收费明细"
TableName = "app_charge_detail"


class ChargeDetail(db.Model):
    """
    收费明细
    """
    __tablename__ = TableName
    # 收费ID
    ChargeID = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
    # 更次ID
    ClassesID = db.Column(db.Integer,nullable=False)
    # 收费类型
    ChargeType = db.Column(db.String(16), nullable=False)
    # 在场ID
    ParkingID = db.Column(db.Integer)
    # 车牌结果
    LicensePlate = db.Column(db.String(16), nullable=False)
    # 时租票号
    TicketNumber = db.Column(db.String(128))
    # 月租卡号
    CardNumber = db.Column(db.String(64))
     # 车型
    VehicleType = db.Column(db.String(16), nullable=False)
    # 月租有效期
    MonthlyValid = db.Column(db.DateTime)
    # 车位类型
    ParkingType = db.Column(db.String(16), nullable=False)
    # 入场时间
    EntranceTime = db.Column(db.DateTime)
    # 收费处
    CashierName = db.Column(db.String(16), nullable=False)
    # 收费员
    UserName = db.Column(db.String(16), nullable=False)
    # 收费类型
    PayMent = db.Column(db.String(16), nullable=False)
    # 金额
    Money = db.Column(db.Float,nullable=False)
    # 收费时间
    ChargeTime = db.Column(db.DateTime)
    # 删除状态
    Deleted = db.Column(db.Boolean, default=False)

    def __init__(self, **kwargs) -> None:
        super().__init__()
        self.ClassesID = kwargs.get('ClassesID')
        self.ChargeType = kwargs.get('ChargeType')
        self.ParkingID = kwargs.get('ParkingID')
        self.LicensePlate = kwargs.get('LicensePlate')
        self.TicketNumber = kwargs.get('TicketNumber')
        self.CardNumber = kwargs.get('CardNumber')
        self.VehicleType = kwargs.get('VehicleType')
        self.MonthlyValid = kwargs.get('MonthlyValid')
        self.ParkingType = kwargs.get('ParkingType')
        entrance_time = kwargs.get('EntranceTime')
        if entrance_time:
            self.EntranceTime = datetime.strptime(entrance_time,'%Y/%m/%d %H:%M:%S')
        self.CashierName = kwargs.get('CashierName')
        self.UserName = kwargs.get('UserName')
        self.PayMent = kwargs.get('PayMent')
        self.Money = kwargs.get('Money')
        self.ChargeTime = datetime.now()

    def datetime_string(self, val):
        """
        datetime转换
        """
        if isinstance(val, datetime):
            return val.strftime('%Y/%m/%d %H:%M:%S')

    def to_dict(self):
        """
        转换键值对
        """
        def convert_data(name):
            val = getattr(self, name)
            if isinstance(val, datetime):
                return val.strftime('%Y/%m/%d %H:%M:%S')
            return val
            
        return dict([(c.name, convert_data(c.name)) for c in self.__table__.columns])

    @staticmethod
    def selected_data(**kwargs):
        """
        选中数据
        """
        charge_id = kwargs.get('ChargeID')
        if charge_id:
            return ChargeDetail.query.filter_by(ChargeID=charge_id).first()

    @staticmethod
    def column_name():
        """
        收费明细标题
        """
        return {
            "ClassesID":"更次ID","ChargeID":"收費ID","ChargeTime":"收費時間","ChargeType":"收費類型","ParkingID":"在場ID","VehicleType":"車輛類型",
            "LicensePlate":"車牌號碼","TicketNumber":"時租票號","CardNumber":"月租卡號","MonthlyValid":"月租有效期","ParkingType":"車位類型",
            "EntranceTime":"入場時間","CashierName":"收費處","UserName":"收費員","PayMent":"支付方式","Money":"收費金額",
        }

    @staticmethod
    def generate_filters(**kwargs):
        """
        筛选器
        """
        filters = set()
        for k, v in kwargs.items():
            if v:
                if hasattr(ChargeDetail, k):
                    if k == 'ChargeType':
                        filters.add(ChargeDetail.ChargeType == v)
                    elif k == 'LicensePlate':
                        filters.add(ChargeDetail.LicensePlate == v)
                    elif k == 'TicketNumber':
                        filters.add(ChargeDetail.TicketNumber == v)
                    elif k == 'CardNumber':
                        filters.add(ChargeDetail.CardNumber == v)
                    elif k == 'VehicleType':
                        filters.add(ChargeDetail.VehicleType == v)
                    elif k == 'ParkingType':
                        filters.add(ChargeDetail.ParkingType == v)
                    elif k == 'CashierName':
                        filters.add(ChargeDetail.CashierName == v)
                    elif k == 'UserName':
                        filters.add(ChargeDetail.UserName == v)
                    elif k == 'PayMent':
                        filters.add(ChargeDetail.PayMent == v)
                    elif k == 'PaidTime':
                        if " - " in v:
                            start, end = [datetime.strptime(i, "%Y/%m/%d %H:%M:%S") for i in v.split(' - ') ]
                            filters.add(ChargeDetail.PaidTime.between(start, end))
        return filters

    @staticmethod
    def insert_data(**kwargs):
        """
        新增
        """
        try:
            r = ChargeDetail(**kwargs)
            db.session.add(r)
            db.session.commit()
            db_logger.debug(f"{TableName} => 新增{DataName}成功：{kwargs}")
            return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 新增{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def delete_data(**kwargs):
        """
        删除
        """
        try:
            r = ChargeDetail.selected_data(**kwargs)
            if r:
                # db.session.delete(r)
                r.Deleted = True
                db.session.commit()
                db_logger.debug(f"{TableName} => 删除{DataName}成功：{kwargs}")
                return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 删除{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def parking_charge(**kwargs):
        """
        收費
        """
        try:
            r = ChargeDetail(**kwargs)
            db.session.add(r)
            db.session.commit()
            db_logger.debug(f"{TableName} => 新增{DataName}成功：{kwargs}")
            return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 新增{DataName}失败：{kwargs} 原因：{e}")
        
    @staticmethod
    def table_init():
        """
        数据初始化
        """
        entrance_time = datetime.now()
        demo_data = [
            {"ChargeType":"Hourly","ParkingID":1,"VehicleType":"Car","LicensePlate":"MC0001",
            "TicketNumber":"","CardNumber":"","ParkingType":"Monthly","EntranceTime":entrance_time,
            "CashierName":"收費處A","UserName":"收費員","PayMent":"Cash","Money":12,'ClassesID':1}
        ]
        for i in demo_data:
            ChargeDetail.insert_data(**i)

